---
--类名: ArenaVs.lua
--创建日期: 2018-2-5
--创建人: 陈小虎
--功能描述: 
--修改内容：
--修改日期:   
--修改人:     
--修改备注: 
--

local MoLayer = require("app.widget.MoLayer")
local AvatarFactotry = require("app.public.avatar.AvatarFactory")

local ArenaVs = class("ArenaVs",function()
    return MoLayer.new()
end)

local SelfTeamTextColor = cc.c3b(27, 39, 58)
local EnemyTeamTextColor = cc.c3b(58, 27, 27)

local FILL_BAR_TIME = 5000

function ArenaVs:ctor()
	--ui根节点
    self.mUINode = cc.uiloader:load(Res.ArenaVsScene)
    self.mUINode:setContentSize(display.ui_width, display.ui_height)
    self.mUINode:setAnchorPoint(0.5, 0.5)
    self.mUINode:setPosition(display.width/2, display.height/2)
    display.setAutoScale(self.mUINode)
    ccui.Helper:doLayout(self.mUINode)
    self:addChild(self.mUINode)
    self.mUINode:setContentSize(cc.size(display.width,display.height))
    ccui.Helper:doLayout(self.mUINode)

    self.mTipsNode = self.mUINode:findChild("Panel/tlt")
    assert(self.mTipsNode)

    -- add init
    self:init()

    --add onEnter onExit
    local function onNodeEvent(event)
        if "enter" == event then
            self:onEnter()
        elseif "exit" == event then
            self:onExit()
        end
    end
    self:registerScriptHandler(onNodeEvent) 
    -- Frame Update
    self:scheduleUpdate(handler(self,ArenaVs.updateFrame))
end

function ArenaVs:init()
    self.mTipsNode:setString(L("loadingtips_919"))

    self.unitLoadList = {}

    self._eventHandles = {}

    local handle = EM:on("onUpdateArenaAllLoadPercent", handler(self, ArenaVs.onUpdateArenaAllLoadPercent))
    table.insert(self._eventHandles, handle)

    local handle = EM:on("onBattleLoadEnd", handler(self, ArenaVs.onSelfArenaLoadEnd))
    table.insert(self._eventHandles, handle)

    local handle = EM:on("onMapChanged", handler(self, ArenaVs.onMapLoaded))
    table.insert(self._eventHandles, handle)

    -- AM.playSoundById(7083)
    AM.play(Res.BattlePvPVsUIEnterSound, false)     
    
    self:setVisible(false)
    self:performWithDelay(function()
        self:setVisible(true)
    end,0.5)
end

function ArenaVs:onMapLoaded()
    if self.isMelee then
        app:sendMsg("PvpModel", "reqFinishLoading", Enums.TeamTarget.melee)
    end
end

function ArenaVs:onExit()
    for _, handle in ipairs(self._eventHandles) do
		EM:remove(handle)
	end
	self._eventHandles = nil
end

function ArenaVs:refreshList(dataList, isSelfTeam)
    local count = #dataList
    local item = nil
    local data
    local prefixName
    local panel = self.mUINode:getChildByName("Panel")
    if isSelfTeam then
        prefixName = "Panel/b_"
    else
        prefixName = "Panel/r_"
    end

    for i=1,5 do
        item = self.mUINode:findChild(prefixName..i)
        if i <= count then
            data = dataList[i]

            --create node
            local node = cc.CSLoader:createNode(Res.PvpLoadingNode)
            node:setPosition(item:getPosition())
            node:setName(item:getName())
            panel:addChild(node)
            item:removeFromParent()
            item = node
            item:setVisible(true)

            --名字
            local nameNode = item:findChild("Panel/name")
            nameNode:setString(data.name)

            --头像
            local headNode = item:findChild("Panel/icon")
            local params = {
                hairID=data.hairID,
                faceID=data.faceID,
                hairColorID = data.hairColorID,
                raceID = data.raceID
            }
            local iconPath = AvatarFactotry.getOrCreateHeroIconPath(params,function(iconPath)
                if cc.isAlive(headNode) then
                    headNode:loadTexture(iconPath)
                end
            end)
            
            
            --print("renderNodeToPng",iconPath)
            --类型
            local typeNode = item:findChild("Panel/type")

            local skillChooseIdList = string.split( data.specialistID, "0" )
		    typeNode:setString( L("class_" .. skillChooseIdList[1] .. "_" .. skillChooseIdList[2] ) .. L("class_"..data.classID) )

            --背景
            local redBgNode = item:findChild("Panel/bg_red")
            local blueBgNode = item:findChild("Panel/bg_blue")
            if isSelfTeam then
                redBgNode:setVisible(false)
                blueBgNode:setVisible(true)

                nameNode:setColor(SelfTeamTextColor)
                typeNode:setColor(SelfTeamTextColor)
            else
                redBgNode:setVisible(true)
                blueBgNode:setVisible(false)

                nameNode:setColor(EnemyTeamTextColor)
                typeNode:setColor(EnemyTeamTextColor)
            end

            --背景
            local numNode = item:findChild("Panel/num")
            local percent = string.format("%d%%",0)
            numNode:setString(percent)

            local maxPercent = math.random(91,99)
            self.unitLoadList[data.uid] = {maxPercent = maxPercent, currentPercent = 0, numNode = numNode}
        else
            item:setVisible(false)
        end
    end
end

function ArenaVs:update(data)
    local upDataList 
    local downDataList 
    if data:selfIsTeamA() then
        upDataList = data.userinfosA
        downDataList = data.userinfosB
    else
        upDataList = data.userinfosB
        downDataList = data.userinfosA
    end

    self.isMelee = data.isMelee
    
    if data:isUsingSelfData() then -- 跨服精英赛修改下方tips 
        self.mTipsNode:setString(L("EliteMatchTip46"))
    end

    --上面的队列 自己队伍
    self:refreshList(upDataList, true)

    --下面的队列 敌方队伍
    self:refreshList(downDataList, false)
end

function ArenaVs:updateFrame(dt)
    for uid,data in pairs(self.unitLoadList) do
        if data.currentPercent < data.maxPercent then
            --还没有达到最大值的
            data.currentPercent = data.currentPercent + ((dt*1000/FILL_BAR_TIME) * data.maxPercent)
            if data.currentPercent > data.maxPercent then
                data.currentPercent = data.maxPercent
            end
            local percent = string.format("%d%%",math.floor(data.currentPercent))
            data.numNode:setString(percent)
        end
    end 
end

--自己的加载结束
function ArenaVs:onSelfArenaLoadEnd()
    local selfUid = UD:getPlayer().uid
    self:updateLoadPercent(selfUid, 100)
end

--更新指定uid的加载进度
function ArenaVs:updateLoadPercent(uid, progress)
    --print("updateLoadPercent==========uid",uid,progress)
    --dump(self.unitLoadList, "updateLoadPercent unitLoadList",6)
    if self.unitLoadList[uid] then
        --print("updateLoadPercent==========currentPercent",self.unitLoadList[uid].currentPercent)
        self.unitLoadList[uid].currentPercent = progress

        local percent = string.format("%d%%",math.floor(self.unitLoadList[uid].currentPercent))
        self.unitLoadList[uid].numNode:setString(percent)
    end
end

--更新所有人的进度
function ArenaVs:onUpdateArenaAllLoadPercent(name, states)
    for k,v in pairs(states) do
        if v.progress == 100 then
            self:updateLoadPercent(v.uid, v.progress)
        end
    end
end

-- 隐藏下面的提示文字
function ArenaVs:hideNoticeTips()
    self.mTipsNode:setVisible(false)
end

return ArenaVs
